<template>
  <div class="detail">
    <div class="back-nav-box">
      <back-nav left-arrow left-text="返回" title="商品详情  "></back-nav>
    </div>

    <div>
      <!-- 图片 -->
      <div class="detail-img">
        <img class="auto-img" :src="productDetail.large_img" alt="" />
      </div>
      <!-- 详情文字内容盒子 -->
      <div class="detail-box">
        <div class="pro-info">
          <div>
            <div class="zh-name">{{ productDetail.name }}</div>
            <div class="en-name">{{ productDetail.enname }}</div>
            <div class="pro-price">&yen;{{ productDetail.price }}</div>
          </div>
          <!-- 规格 -->
          <div class="pro-rule">
            <div
              class="pro-rule-item"
              v-for="(item, index) in productDetail.rules"
              :key="index"
            >
              <div class="pro-rule-title">{{ item.title }}</div>
              <div class="pro-sub-rule">
                <div
                  class="pro-sub-rule-item"
                  :class="{ active: item.activeIndex == i }"
                  v-for="(v, i) in item.rules"
                  :key="i"
                  @click="toggleRule(item, i)"
                >
                  {{ v.title }}
                </div>
              </div>
            </div>
          </div>
          <!-- 选择数量 -->
          <div class="select-count">
            <div class="select-text">选择数量</div>
            <div class="select-box">
              <van-stepper
                v-model="count"
                theme="round"
                button-size="22"
                disable-input
              />
            </div>
          </div>
          <!-- 描述 -->
          <div class="describe">
            <div class="describe-title">商品描述</div>
            <div class="describe-text">
              <div
                class="describe-text-item"
                v-for="(item, index) in productDetail.desc"
                :key="index"
              >
                {{ index + 1 }}、{{ item }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <van-goods-action>
      <van-goods-action-icon
        icon="cart-o"
        :badge="shopbagCount == 0 ? '' : shopbagCount"
        text="购物袋"
        @click="jumpShopbag"
      />
      <van-goods-action-icon
        icon="star"
        :text="islike ? '已收藏' : '未收藏'"
        :color="islike ? '#f00' : '#d0d0d0'"
        @click="likeAndNotlike"
      />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        color="#B4D3FB"
        @click="addShopbag"
      />
      <van-goods-action-button
        type="danger"
        text="立即购买"
        color="#0099ff"
        @click="makeorder"
      />
    </van-goods-action>
  </div>
</template>

<script>
import BackNav from "../components/BackNav.vue";
export default {
  name: "Detail",
  components: {
    BackNav,
  },
  data() {
    return {
      //选择商品件数
      count: 1,
      //商品pid
      pid: "",
      //商品详情数据
      productDetail: {},
      //是否收藏
      islike: false,
      //购物袋商品总数量
      shopbagCount: 0,
      //商品购物标识
      sid: "",
    };
  },
  created() {
    //截取商品pid
    this.pid = this.$route.params.pid;
    this.getProductDetailByPid();
  },
  methods: {
    // 根据商品pid查询商品数据
    getProductDetailByPid() {
      this.axios({
        method: "get",
        url: "/productDetail",
        params: {
          //appkey参数在拦截器中做优化处理
          pid: this.pid,
        },
      })
        .then((res) => {
          // 
          if (res.data.code == 600) {
            let data = res.data.result[0];
            data.desc = data.desc.split(/\n/);
            // 
            // 处理规格数据
            let ruleData = ["cream", "sugar", "milk", "tem"];
            let rules = [];
            ruleData.forEach((v) => {
              if (!data[v]) {
                return;
              }
              let r = {
                title: data[`${v}_desc`],
                //默认激活的规格
                activeIndex: 0,
                rules: [],
              };
              let rs = data[v].split(/\//);
              rs.forEach((item) => {
                let subRule = {
                  title: item,
                };
                r.rules.push(subRule);
              });
              rules.push(r);
            });
            // 处理获取到的数据
            data.rules = rules;
            this.productDetail = data; 
          }
        })
        .catch((err) => {
          
        });
    },
    // 切换规格的方法
    toggleRule(item, index) {
      if (item.activeIndex == index) {
        return;
      }
      item.activeIndex = index;
    },
    //收藏商品
    likeAndNotlike() {
      // 发起收藏或者取消收藏请求
      let url = "";
      if (this.islike) {
        //取消收藏
        url = "/notlike";
      } else {
        //收藏
        url = "/like";
      }
      this.axios({
        method: "post",
        url,
        // 接受这种参数格式 data:`appkey=''&pid=''&tokenString=''`,
        //服务端不接受对象格式,(请求拦截器中)做字符串拼接处理
        data: {
          pid: this.pid,
          // tokenString:'用户token在拦截器中处理',
          //appkey参数在拦截器中处理
        },
      })
        .then((res) => {
          // 
          //用户未登录
          if (res.data.code === 700) {
            // Toast 是一个 View 视图，快速的为用户显示少量的信息。
            this.$toast(res.data.msg);
            //跳转到登录页面
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
          }
          //用户已登录
          this.$toast(res.data.msg);
          //用户未收藏商品
          if (res.data.code == 800) {
            this.islike = true;
          }
          //用户已收藏商品
          else if (res.data.code == 900 && res.data.result == 1) {
            this.islike = false;
          }
        })
        .catch((err) => {
          
        });
    },
    //查询用户是否收藏该商品
    findUserLike() {
      this.axios({
        method: "get",
        url: "/findlike",
        params: {
          pid: this.pid,
        },
      })
        .then((res) => {
          // 
          if (res.data.code == 1000 && res.data.result.length == 1) {
            //该商品已经被收藏
            this.islike = true;
          }
        })
        .catch((err) => {
          
        });
    },
    //抽取添加购物车的请求
    addPro() {
      //获取商品
      let rules = [];
      this.productDetail.rules.forEach((v) => {
        rules.push(v.rules[v.activeIndex].title);
      });
      return this.axios({
        method: "post",
        url: "/addShopcart",
        data: {
          //appkey参数在拦截器中做优化处理
          pid: this.pid,
          //数组以'/'连接成字符串
          rule: rules.join("/"),
          count: this.count,
        },
      });
    },
    //加入购物袋
    addShopbag() {
      this.addPro()
        .then((res) => {
          
          //  

          // 用户未登录
          if (res.data.code == 700) {
            //跳到登录页面
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 1000);
          }
          //用户提醒
          this.$toast(res.data.msg);
          if (res.data.code == 3000) {
            //累加购物车商品数量
            this.shopbagCount += this.count;
            //拿到购物车标识
            this.sid = res.data.sid;
          }
        })
        .catch((err) => {
          
        });
    },
    //查询用户的购物袋数量
    findUserShopbagCount() {
      this.axios({
        method: "get",
        url: "/shopcartCount",
      })
        .then((res) => {
        //   
          if (res.data.code == 4000) {
            this.shopbagCount = res.data.result;
            // 
          }
        })
        .catch((err) => {
          
        });
    },
    //点击购物袋跳转购物袋页面
    jumpShopbag() {
      this.$router.push({ name: "Shopbag" });
    },
    //立即购买
    makeorder() {
      let that = this;
      async function add() {
        let end = await that.addPro().then((res) => {
          let sid = res.data.sid;
        //   
          return [sid];
        });
        // 
        that.$router.push({ name: "MakeOrder", params: { sids: end} });
      }
      add();

    },
  },
};
</script>

<style lang='less' scoped>
@import url("../assets/base.less");

.detail {
  // 修改框架内容颜色
  /deep/ .van-stepper--round .van-stepper__plus {
    background-color: @mainColor;
  }
  /deep/ .van-stepper--round .van-stepper__minus {
    color: @mainColor;
    border-color: @mainColor;
  }
  /deep/ .van-goods-action-button--warning {
    background-color: #dfab6f !important;
  }
  /deep/ .van-goods-action-button--danger {
    background-color: #8b5729 !important;
  }
  .back-nav-box {
    position: sticky;
    top: 0;
    color: @mainColor;
  }
  padding-bottom: 50px;
  .describe-text {
    color: #555;
    margin-top: 10px;
  }
  .describe-text-item {
    margin-bottom: 5px;
  }
  .describe-title {
    font-size: 14px;
  }
  .describe {
    margin-top: 20px;
  }
  .select-box {
    margin-left: auto;
  }
  .select-text {
    font-size: 14px;
    margin-right: 10px;
  }
  .select-count {
    margin-top: 20px;
    padding: 20px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
  }
  .pro-sub-rule-item {
    width: 60px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    background-color: #e8e8e8;
    margin-right: 10px;
    border-radius: 12px;
    &:last-child {
      margin-right: 0;
    }
    &.active {
      background-color: @mainColor;
      color: #fff;
    }
  }
  .pro-sub-rule {
    display: flex;
  }
  .pro-rule-title {
    width: 50px;
    height: 24px;
    line-height: 24px;
    font-size: 14px;
  }
  .pro-rule-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .pro-rule {
    margin-top: 30px;
  }
  .zh-name {
    font-size: 14px;
    margin-bottom: 5px;
  }
  .en-name {
    color: #999;
    margin-bottom: 5px;
    // color:#83653C;
    // color:#94C1FF;
  }
  .pro-price {
    margin-left: auto;
    font-size: 14px;
    color: @priceColor;
    font-weight: bold;
  }
  .pro-info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  .detail-box {
    margin: 0 10px;
    padding: 10px;
    background-color: #fff;
    position: relative;
    top: -20px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .detail-img {
    background-color: #e8e8e8;
  }
}
</style>